package com.firmboy.thread.lock;

import org.junit.Test;

import java.util.Random;

/**
 * 读写锁测试
 *
 * @author firmboy
 * @create 2018-05-17 下午6:37
 **/
public class ReadWriteLockTest {

    @Test
    public void test(){
        final Data data = new Data();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10000;i++){
                    data.set(new Random().nextInt(100));
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10000;i++){
                    data.get();
                }
            }
        });

        thread1.start();
        thread2.start();
        try{
           Thread.sleep(100000);

        }catch(Exception e){
            e.printStackTrace();
        }



    }

}

class Data{
    private int data;

    public synchronized void set(int data){
        System.out.println(Thread.currentThread().getName()+"准备写入数据");
        try{
            Thread.sleep(20);
        }catch(Exception e){
            e.printStackTrace();
        }
        this.data = data;
        System.out.println(Thread.currentThread().getName()+"写入"+this.data);
    }

    public synchronized void get(){
        System.out.println(Thread.currentThread().getName()+"准备读取数据");
        try{
            Thread.sleep(20);
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"读取"+this.data);

    }
}
